package com.labuladong;

/**
 * 项目名称: java_algorithm
 * @ClassName Binary
 * @Description 二分查找算法
 * @Author huipanxing huipanxing@chinasofti.com   @Date 2022/6/24 14:32
 */
public class Binary {

    public static void main(String[] args) {
        int[] nums = {1, 2, 5, 5, 5, 5, 5, 8, 9};
        int target = 5;
//        int index = findIndex(nums, target, 0, nums.length - 1);
        int index = findIndex3(nums, target);
        System.out.println(index);
    }

    /**
     * @param nums
     * @param target
     * @param left
     * @param right
     * @return int
     * 二分查找递归方式
     */
    public static int findIndex(int[] nums, int target, int left, int right) {
        if (nums.length == 0) {
            return -1;
        }
        int min = left + (right - left) / 2;
        if (target == nums[min]) {
            return min;
        } else if (target > nums[min]) {
            left = min + 1;
        } else if (target < nums[min]) {
            right = min - 1;
        }
        return findIndex(nums, target, left, right);
    }

    /**
     * @param nums
     * @param target
     * @return int
     * 二分查找while循环方式
     */
    public static int findIndex1(int[] nums, int target) {
        if (nums.length == 0) {
            return -1;
        }
        int left = 0;
        int right = nums.length - 1;
        while (left < right) {
            int min = left + (right - left) / 2;
            if (target == nums[min]) {
                return min;
            } else if (target > nums[min]) {
                left = min + 1;
            } else if (target < nums[min]) {
                right = min - 1;
            }
        }
        return -1;
    }

    /**
     * @param nums
     * @param target
     * @return int
     * 二分查找连续数字寻找左边界的值
     */
    public static int findIndex2(int[] nums, int target) {
        if (nums.length == 0) {
            return -1;
        }
        int left = 0;
        int right = nums.length - 1;
        while (left < right) {
            int min = left + (right - left) / 2;
            if (target == nums[min]) {
                right = min;
            } else if (target > nums[min]) {
                left = min + 1;
            } else if (target < nums[min]) {
                right = min - 1;
            }
        }
        return left;
    }

    /**
     * @param nums
     * @param target
     * @return int
     * 二分查找连续数字寻找右边界的值
     */
    public static int findIndex3(int[] nums, int target) {
        if (nums.length == 0) {
            return -1;
        }
        int left = 0;
        int right = nums.length - 1;
        while (left < right) {
            int min = left + (right - left) / 2;
            if (target == nums[min]) {
                left = min+1;
            } else if (target > nums[min]) {
                left = min + 1;
            } else if (target < nums[min]) {
                right = min - 1;
            }
        }
        return right;
    }

}
